﻿Ext.define("PSI.Knowledge.KnowledgeBackMain", {

    createUI: function () {
        var panel = Ext.create("Ext.panel.Panel", {
            layout: "border",
            title: '知识管理后台',
            tbar: [
               { text: "新增文章类别", handler: function () { this.onAddEssayType() }, iconCls: "psi-button-add", scope: this },
               { text: "编辑文章类别", handler: function () { this.onEdithEssaytype() }, iconCls: "psi-button-edit", scope: this },
               { text: "删除文章类别", handler: this.onDeleteEssayType, iconCls: "psi-button-delete", scope: this }, "-",
               { text: "发表文章", handler: function () { this.onAddArcitle(null) }, iconCls: "psi-button-add", scope: this },
               { text: "编辑文章", handler: this.onEditArcitle, iconCls: "psi-button-edit", scope: this },
               { text: "删除文章", handler: this.onDeleteArcitle, iconCls: "psi-button-delete", scope: this }, "-",

               {
                   text: "关闭", iconCls: "psi-button-exit", handler: function () {
                       location.replace("/");
                   }
               }
            ],
            items: [
                {
                    xtype: "panel",
                    title: "文章类别",
                    width: "20%",
                    region: "west",
                    layout: "fit",
                    items: [
                        this.getEssayTypeItem()
                    ]
                }, {
                    xtype: "panel",
                    region: "center",
                    width: "80%",
                    layout: "fit",
                    items: [
                        this.getAcrItems()
                    ]
                }
            ]

        })
        this.panel = panel;

    },

    getMainPanel: function () {
        return this.panel;
    },

    onAddEssayType: function (entity) {
        var windowT = Ext.create("Ext.window.Window", {
            title: entity == null ? "新增文章类别" : "编辑文章类别",
            modal: true,
            onEsc: Ext.emptyFn,
            width: 400,
            height: 150,
            layout: "fit",
            items: [
               {
                   xtype: "form",
                   id: "essayform",
                   height: "100%",
                   layout: "form",
                   defaultType: 'textfield',
                   bodyPadding: '30 10 0',
                   fieldDefaults: {
                       labelWidth: 70,
                       labelAlign: "right",
                       labelSeparator: "",
                       msgTarget: 'side'
                   },
                   items: [
                       {
                           id: "id",
                           xtype: "hidden",
                           name: "id",
                           value: entity == null ? null : entity.id
                       }, {
                           fieldLabel: "类别名称：",
                           beforeLabelTextTpl: PSI.Const.REQUIRED,
                           allowBlank: false,
                           id: "typename",
                           name: "name",
                           value: entity == null ? null : entity.name
                       }
                   ],
                   buttons: [
                      {
                          text: "确定",
                          formBind: true,
                          iconCls: "psi-button-ok",
                          handler: this.onOK,
                          scope: this
                      },
                      {
                          text: "取消", handler: function () {
                              windowT.close();
                          }, scope: this
                      }
                   ]
               }

            ]

        })
        windowT.show();
        this.windowsT = windowT;
    },

    onEdithEssaytype: function () {
        var grid = Ext.getCmp("ktypeitem");
        var items = grid.getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("请选择一条要编辑的文章类别！");
            return;
        }

        this.onAddEssayType(items[0].getData());
    },

    onDeleteEssayType: function () {
        me = this;
        var grid = Ext.getCmp("ktypeitem");
        var items = grid.getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("请选择一条要删除的文章类别！");
            return;
        }
        PSI.MsgBox.confirm("确定是否要删除记录！", function () {
            var iden = items[0].getData().id;
            var el = Ext.getBody();
            el.mask("正在删除中...");
            Ext.Ajax.request({
                url: "/Knowledge/DeleteKtype",
                method: "POST",
                params: { id: iden },
                callback: function (options, success, response) {
                    el.unmask();
                    if (success) {
                        var data = Ext.JSON.decode(response.responseText);
                        if (data.success) {
                            PSI.MsgBox.showInfo("成功完成删除操作", function () {
                                var ste = Ext.data.StoreManager.lookup("ktype")
                                ste.load();
                            });
                        } else {
                            PSI.MsgBox.showInfo(data.msg);
                        }
                    } else {
                        PSI.MsgBox.showInfo("网络错误");
                    }
                }

            });

        })
    },

    onOK: function () {
        var me = this;
        var f = Ext.getCmp("essayform");
        var el = f.getEl();
        el.mask("数据保存中...");
        f.submit({
            url: "/Knowledge/AddEssay",
            method: "POST",
            success: function (form, action) {
                el.unmask();
                PSI.MsgBox.showInfo("数据保存成功", function () {

                    //var wnd = Ext.getCmp("wnd");
                    me.windowsT.close();
                    //sd = me.parentForm.orgTree;

                    var ste = Ext.data.StoreManager.lookup("ktype")
                    ste.load();
                    // window.location.reload();
                });
            },
            failure: function (form, action) {
                el.unmask();
                PSI.MsgBox.showInfo("服务器或网络问题,数据保存失败。", function () {

                });
            }
        })

    },

    getEssayTypeItem: function () {
        me = this;
        var emodel = Ext.define("moldes", {
            extend: "Ext.data.Model",
            fields: ["id", "name"]
        })
        var tx = Ext.create("Ext.data.Store", {
            model: emodel,
            storeId: 'ktype',
            proxy: {
                type: 'ajax',
                url: '/Knowledge/GetKtypeItems',
                extraParams: {},
                actionMethods: { read: 'POST' },
                reader: {
                    type: 'json',
                    root: 'Data'
                }
            },
            autoLoad: true
        })
        // tx.load();
        return Ext.create("Ext.grid.Panel", {
            viewConfig: { loadingText: "数据加载中...." },
            id: "ktypeitem",
            store: Ext.data.StoreManager.lookup("ktype"),
            columnLines: true,
            columns: [
                   Ext.create("Ext.grid.RowNumberer", { text: "序号", width: "15%", align: "center" }),
                   { header: '', dataIndex: 'id', hidden: true },
                   { header: "类别名称", dataIndex: 'name', menuDisabled: true, width: "84%" }
            ],
            listeners: {

                itemdblclick: function (view, record, item, index, e, eOpts) {
                    me.onAddEssayType(record.raw);

                },
                select:function( me, record, item, index, e, eOpts ) {
                    var stro=Ext.data.StoreManager.lookup("acrstore")

                    stro.load({
                        params: {
                            pareid: record.raw.id
                        
                        }
                    })
                }

            }


        });

    },

    onAddArcitle: function (entity) {
        var f1, f2;
        if (entity != null)
        {
            if (entity.FileOne != "")
            {
                var cc=entity.FileOne.split("_");
                f1 = cc[1];
            }
            if (entity.FileTwo != "") {
                var cc = entity.FileTwo.split("_");
                f2 = cc[1];
            }
        }
        var windowArcitle = Ext.create("Ext.window.Window", {
            modal: true,
            id: 'arcform',
            title: entity == null ? "发表文章" : "编辑文章",
            width: 700,
            height: 430,
            layout: "fit",
            items: [
                {
                    xtype: 'form',
                    id: 'arcitlewin',
                    border: 0,
                    layout: "vbox",
                    //    collapsible: true,
                    frame: true,
                    defaultType: 'textfield',
                    fieldDefaults: {
                        labelAlign: 'right',
                        labelWidth: 70,
                        msgTarget: 'side'
                    },
                    bodyPadding: '5 5 0',
                    items: [
                        {
                            id: "themeid",
                            xtype: "hidden",
                            name: "id",
                            value: entity == null ? null : entity.id
                        }, {
                            xtype: 'combo',
                            id: "etype",
                            fieldLabel: '文章类别',
                            store: Ext.data.StoreManager.lookup("ktype"),
                            displayField: 'name',
                            editable: false,
                            name: 'etype',
                            beforeLabelTextTpl: PSI.Const.REQUIRED,
                            allowBlank: false,
                            valueField: 'id',
                            value :entity==null?null:entity.KTypeID,
                            width: 250,
                            anchor: '100%'
                        },
                        {
                            fieldLabel: '文章标题',
                            name: 'title',
                            value: entity == null ? "" : entity.title,
                            beforeLabelTextTpl: PSI.Const.REQUIRED,
                            allowBlank: false,
                            width: 650,
                            anchor: '100%'
                        }, {
                            xtype: 'container',
                            layout: 'hbox',
                            width: 500,
                            margin: '0 5 5 0',
                            items: [{
                                xtype: 'filefield',
                                fieldLabel: '添加附件1',
                                name: 'file1',
                                buttonOnly: true,
                                buttonText: "浏览文件",
                                flex: 1,
                                listeners: {
                                    'change': function (fb, v) {
                                        var f = Ext.getCmp("arcitlewin");
                                        var el = f.getEl();
                                        var index = v.split("\\");
                                       
                                        var parm = {
                                            filename: PSI.Const.NewGuid + "_" + index[(index.length)-1],
                                            filetype: 1
                                        }
                                        el.mask("文件保存中...");
                                        f.submit({
                                            url: "/Knowledge/UploadFile",
                                            method: "POST",
                                            params: parm,
                                            success: function (form, action) {
                                                el.unmask();
                                                Ext.getCmp("f_one").setText(index[(index.length) - 1]);
                                                Ext.getCmp("readyone").setValue(parm.filename);
                                            },
                                            failure: function (form, action) {
                                                el.unmask();
                                                PSI.MsgBox.showInfo("服务器或网络问题,文件上传失败。", function () {

                                                });
                                            }
                                        });
                                    }
                                }
                            }, {
                                xtype: 'label',
                                id: 'f_one',
                                text: f1,
                                flex: 2

                            }, {
                                xtype: 'hidden',
                                id: 'readyone',
                                value: entity == null ? "" : entity.FileOne,
                                name: 'readyone'
                            }]
                        }, {
                            xtype: 'container',
                            layout: 'hbox',
                            width: 500,
                            margin: '0 5 5 0',
                            items: [{
                                xtype: 'filefield',
                                fieldLabel: '添加附件2',
                                name: 'file2',
                                buttonOnly: true,
                                buttonText: "浏览文件",
                                flex: 1,
                                listeners: {
                                    'change': function (fb, v) {
                                        var f = Ext.getCmp("arcitlewin");
                                        var el = f.getEl();
                                        el.mask();
                                        var index = v.split("\\");
                                        var parm = {
                                            filename: PSI.Const.NewGuid + "_" + index[2],
                                            filetype: 2
                                        }
                                        el.mask("文件保存中...");
                                        f.submit({
                                            url: "/Knowledge/UploadFile",
                                            method: "POST",
                                            params: parm,
                                            success: function (form, action) {
                                                el.unmask();
                                                Ext.getCmp("f_two").setText(index[2]);
                                                Ext.getCmp("readytwo").setValue(parm.filename);
                                            },
                                            failure: function (form, action) {
                                                el.unmask();
                                                PSI.MsgBox.showInfo("服务器或网络问题,文件上传失败。", function () {

                                                });
                                            }
                                        });
                                    }
                                }
                            }, {
                                xtype: 'label',
                                id: 'f_two',
                                text: f2,
                                flex: 2
                            }, {
                                xtype: 'hidden',
                                id: 'readytwo',
                                value: entity == null ? "" : entity.FileTwo,
                                name: 'readytwo'
                            }]
                        }, {
                            xtype: 'htmleditor',
                            name: 'bio',
                            fieldLabel: '文章内容',
                            beforeLabelTextTpl: PSI.Const.REQUIRED,
                            allowBlank: false,
                            value: entity == null ? "" : entity.Contents,
                            height: 240,
                            width: 650,
                            anchor: '100%'
                        }

                    ]
                }

            ], buttons: [
                {
                    text: entity == null ? "发布" : "编辑",
                    formBind: true,
                    iconCls: "psi-button-ok",
                    handler: this.releayOK,
                    scope: this
                },
                {
                    text: "取消", handler: function () {
                        windowArcitle.close();
                    }, scope: this
                }
            ]

        }).show();
        this.windowArcitle = windowArcitle;
    },

    onEditArcitle: function () {
        var grid = Ext.getCmp("kthemeitem");
        var items = grid.getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("请选择一条要编辑的文章！");
            return;
        }

        this.onAddArcitle(items[0].getData());
    },

    onDeleteArcitle: function () {
        me = this;
        var grid = Ext.getCmp("kthemeitem");
        var items = grid.getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("请选择一条要删除的文章！");
            return;
        }
        PSI.MsgBox.confirm("确定是否要删除记录！", function () {
            var iden = items[0].getData().id
            var el = Ext.getBody();
            el.mask("正在删除中...");
            Ext.Ajax.request({
                url: "/Knowledge/DelAcr",
                method: "POST",
                params: { id: iden },
                callback: function (options, success, response) {
                    el.unmask();
                    if (success) {
                        var data = Ext.JSON.decode(response.responseText);
                        if (data.success) {
                            PSI.MsgBox.showInfo("成功完成删除操作", function () {

                                var gridkEassy = Ext.getCmp("ktypeitem");
                                var store = Ext.data.StoreManager.lookup("ktype");
                                record = store.getById(items[0].getData().KTypeID);
                                gridkEassy.getSelectionModel().clearSelections();
                                gridkEassy.getSelectionModel().select(record);
                            });
                        } else {
                            PSI.MsgBox.showInfo("删除失败!");
                        }
                    } else {
                        PSI.MsgBox.showInfo("网络错误");
                    }
                }

            })
        });

    },
  
    getAcrItems: function () {
        me = this;
        Ext.define("acrmodel", {
            extend: "Ext.data.Model",
            fields: ["id", "KTypeID", "title", "Contents", "FileOne", "FileTwo", "CreatTime", "CreatPerson"]

        })
        Ext.create("Ext.data.Store", {
            model: "acrmodel",
            storeId: "acrstore",
            proxy: {
                type: 'ajax',
                url: '/Knowledge/GetEassyAcrItems',
                extraParams: {},
                actionMethods: { read: 'POST' },
                reader: {
                    type: 'json',
                    root: 'Data'
                }
            },
            autoLoad: true

        })

      return  Ext.create("Ext.grid.Panel", {
            viewConfig: { loadingText: "数据加载中...." },
            id: "kthemeitem",
            store: Ext.data.StoreManager.lookup("acrstore"),
            columnLines: true,
            columns: [
                   Ext.create("Ext.grid.RowNumberer", { text: "序号",width:"5%", align: "center" }),
                   { header: '', dataIndex: 'id', hidden: true },
                   { header: "文章标题", dataIndex: 'title', menuDisabled: true, width: "30%" },
                   {
                       header: "附件1", dataIndex: 'FileOne', menuDisabled: true, width: "20%",
                       renderer: function (value) {
                           if (value && value.toString() != "") {
                               var Array = value.split('_');
                               return Array[1].toString();
                           }
                       }
                   },
                   {
                       header: "附件2", dataIndex: 'FileTwo', menuDisabled: true, width: "20%",
                       renderer: function (value) {
                           if (value && value.toString() != "") {
                               var Array = value.split('_');
                               return Array[1].toString();
                           }
                       }
                   },
                   {
                       header: "创建时间", dataIndex: 'CreatTime', menuDisabled: true, width: "15%",
                       renderer: function (value) {
                           if (value) {
                               var dt = eval("new " + value.substr(1, value.length - 2)).toString();
                               return Ext.util.Format.date(dt, "Y-m-d H:i");//"Y年m月d日H时i分s秒"  

                           }
                       }
                   },
                   { header: "创建人", dataIndex: 'CreatPerson', menuDisabled: true, width: "9%" }
                  // { header: "类别名称", dataIndex: 'name', menuDisabled: true, width: "84%" },
            ],
            listeners: {
                itemdblclick: function (view, record, item, index, e, eOpts) {
                    me.onAddArcitle(record.raw);

                }
            }

        })

    },

    releayOK: function () {
        me = this;
        var f = Ext.getCmp("arcitlewin");
        var el = f.getEl();
        f.submit(
        {
            url: "/Knowledge/ReleaseEassy",
            method: "POST",
            success: function (from, action) {
                el.unmask();
                var info;
                if (Ext.getCmp("themeid").getValue() != "") {
                    info = "文章编辑完成！";
                }
                else {
                    info = "文章发布成功！";
                }
                PSI.MsgBox.showInfo(info, function () {
                    var gridkEassy = Ext.getCmp("ktypeitem");
                    var store = Ext.data.StoreManager.lookup("ktype");
                    record = store.getById(Ext.getCmp("etype").getValue());
                    gridkEassy.getSelectionModel().clearSelections();
                    gridkEassy.getSelectionModel().select(record);
                    me.windowArcitle.close();
                });
            }
        })

    }

})